<template>
  <div class="shell">
    <div class="btn">
      <el-button @click="showForm" size="small" type="success">创建连接</el-button>
    </div>
    <div class="table">
      <el-table height="100%" border highlight-current-row :data="dataList">
        <el-table-column label="序号" type="index" width="70px" align="center"/>
        <el-table-column show-overflow-tooltip label="uuid" prop="uuid" align="center"/>
        <el-table-column show-overflow-tooltip label="名称" prop="name" align="center"/>
        <el-table-column show-overflow-tooltip label="主机地址" prop="host" align="center"/>
        <el-table-column show-overflow-tooltip label="登录名" prop="username" align="center"/>
        <el-table-column show-overflow-tooltip label="端口" prop="port" align="center"/>
        <el-table-column width="180px" align="center" label="操作">
          <template #default="{row}">
            <el-button @click="createWindow('/ssh',row)" type="text">ssh</el-button>
            <el-button @click="editItem(row)" type="text">编辑</el-button>
            <el-button style="color: red" @click="delSsh(row)" type="text">删除</el-button>
            <el-button @click="createWindow('/sftp',row)" type="text">sftp</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
          :page-size="pagination.page_size"
          :pager-count="pagination.page"
          layout="prev, pager, next"
          :total="pagination.total"
      />
    </div>

    <el-dialog :title="type==='add'?'创建连接':'编辑连接'" :close-on-click-modal="false" v-model="visible">
      <el-form label-width="80px" ref="formRef" :rules="rules" :model="form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="主机地址" prop="host">
          <el-input v-model="form.host" clearable></el-input>
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password type="password" v-model="form.password" clearable></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button @click="toCreate" type="primary">连接</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import {nextTick, onMounted, reactive, ref} from 'vue';
import 'xterm/css/xterm.css';
import {ElMessage, ElMessageBox} from "element-plus";
import * as uuid from "uuid";
import local from '@/axios/local'

const socket = ref(window.$io)
const pagination = reactive({
  page_size: 10,
  page: 1,
  total: 0
})
const visible = ref(false);  // 获取 DOM 容器
let type = ref();
let formRef = ref();
let dataList = ref([]);
let form = ref({});
let rules = {
  name: {required: true, trigger: 'blur', message: '请输入名称'},
  host: {required: true, trigger: 'blur', message: '请输入主机地址'},
  port: {required: true, trigger: 'blur', message: '请输入端口'},
  username: {required: true, trigger: 'blur', message: '请输入用户名'},
  password: {required: true, trigger: 'blur', message: '请输入密码'},
};

async function delSsh(row) {
  ElMessageBox.confirm(
      '确定删除?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await local.post('/ssh/delSsh', {id: row.id})
        ElMessage.success('删除成功')
        await getData()
      })
      .catch(() => {

      })

}

async function createWindow(route, row) {
  socket.value.emit('ssh.createWindow', {
    ...row,
    ...{
      route
    }

  })
}

function showForm() {
  type.value = 'add'
  visible.value = true
  form.value = {
    port: 22,
    username: 'root',
    password: 'Zzq19990506!!',
    host: '140.143.235.209',
    name: '测试1'
  }
}

function toCreate() {
  formRef.value.validate(async v => {
    if (v) {
      let data = await createSsh(form.value)
      if (type.value === 'add') {
        await local.post('/ssh/createOrUpdate', form.value)
        // terminalList.value.push(data)
        // tabIndex.value = terminalList.value.length - 1
        // initTerm(data, tabIndex.value)
        // setStorage()
        // ElMessage.success(`连接${form.value.host}成功`)

      } else {
        // setStorage()
        // ElMessage.success(`修改连接${form.value.host}成功`)
      }
      visible.value = false

    }
  })
}

function editItem(item) {
  type.value = 'edit'
  form.value = JSON.parse(JSON.stringify(item))
  visible.value = true
}

function createSsh(data) {
  return new Promise((resolve, reject) => {
    socket.value.emit('ssh.connSsh', data, r => {
      console.log(r, 'r')
      if (r.code === 200) {
        data.uuid = data.uuid ? data.uuid : uuid.v4().replaceAll('-', '')
        resolve(data)
      } else {
        ElMessage.error(`连接${data.host}失败--${r.msg}`)
        reject()

      }
    })
  })
}


async function getData() {
  let res = await local.get('/ssh/getSsh', {params: pagination})
  pagination.total = res.total
  dataList.value = res.data
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>

.shell {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;

  .pagination {
    display: flex;
    justify-content: center;
  }

  .btn {
    padding: 10px;
    display: flex;
    justify-content: flex-end;
  }

  .table {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;

    .container-item {
      height: 100%;
    }
  }
}
</style>
